<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      style="display: none"
      ref="upload"
      v-if="type === 'url'"
    />
    <div class="editor" ref="editor" :style="styles"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed } from 'vue'
import Quill from 'quill'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// import { getToken } from "@/utils/auth"

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  height: {
    type: Number,
    default: 500
  },
  minHeight: {
    type: Number,
    default: null
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  fileSize: {
    type: Number,
    default: 10
  },
  type: {
    type: String,
    default: "url"
  }
})

const emit = defineEmits([
  'update:modelValue', 
  'on-change',
  'on-text-change',
  'on-selection-change',
  'on-editor-change'
])

const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
const headers = ref({
  // Authorization: "Bearer " + getToken()
})

const editor = ref(null)
const upload = ref(null)
const quillInstance = ref(null)
const currentValue = ref(props.modelValue)

const styles = computed(() => {
  const style = {}
  if (props.minHeight) style.minHeight = `${props.minHeight}px`
  if (props.height) style.height = `${props.height}px`
  return style
})

const options = {
  theme: "snow",
  bounds: document.body,
  debug: "warn",
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ list: "ordered" }, { list: "bullet" }],
      [{ indent: "-1" }, { indent: "+1" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ align: [] }],
      ["clean"],
      ["link", "image", "video"]
    ]
  },
  placeholder: "请输入内容",
  readOnly: props.readOnly
}

const initQuill = () => {
  quillInstance.value = new Quill(editor.value, options)

  if (props.type === 'url') {
    const toolbar = quillInstance.value.getModule('toolbar')
    toolbar.addHandler('image', () => {
      upload.value.$el.querySelector('input').click()
    })
  }

  quillInstance.value.clipboard.dangerouslyPasteHTML(currentValue.value)

  quillInstance.value.on('text-change', () => {
    const html = editor.value.children[0].innerHTML
    const text = quillInstance.value.getText()
    currentValue.value = html
    emit('update:modelValue', html)
    emit('on-change', { html, text, quill: quillInstance.value })
  })

  quillInstance.value.on('text-change', (delta, oldDelta, source) => {
    emit('on-text-change', delta, oldDelta, source)
  })

  quillInstance.value.on('selection-change', (range, oldRange, source) => {
    emit('on-selection-change', range, oldRange, source)
  })

  quillInstance.value.on('editor-change', (eventName, ...args) => {
    emit('on-editor-change', eventName, ...args)
  })
}

watch(() => props.modelValue, (newVal) => {
  if (newVal !== currentValue.value) {
    currentValue.value = newVal || ''
    if (quillInstance.value) {
      quillInstance.value.clipboard.dangerouslyPasteHTML(currentValue.value)
    }
  }
})

onMounted(initQuill)

onBeforeUnmount(() => {
  if (quillInstance.value) {
    quillInstance.value = null
  }
})

const handleBeforeUpload = (file) => {
  const validTypes = ["image/jpeg", "image/jpg", "image/png", "image/svg"]
  if (!validTypes.includes(file.type)) {
    ElMessage.error('图片格式错误!')
    return false
  }

  if (props.fileSize && file.size / 1024 / 1024 >= props.fileSize) {
    ElMessage.error(`上传文件大小不能超过 ${props.fileSize} MB!`)
    return false
  }

  return true
}

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    const quill = quillInstance.value
    const position = quill.getSelection()?.index || 0
    quill.insertEmbed(position, 'image', import.meta.env.VITE_APP_BASE_API + res.fileName)
    quill.setSelection(position + 1)
  } else {
    ElMessage.error('图片插入失败')
  }
}

const handleUploadError = () => {
  ElMessage.error('图片插入失败')
}
</script>

<style scoped>
.editor,
:deep(.ql-toolbar) {
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.quill-img {
  display: none;
}

:deep(.ql-snow .ql-tooltip[data-mode="link"]::before) {
  content: "请输入链接地址:";
}

:deep(.ql-snow .ql-tooltip.ql-editing a.ql-action::after) {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}
</style>
<style>
.editor, .ql-toolbar {
  white-space: pre-wrap !important;
  line-height: normal !important;
}
.quill-img {
  display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}
.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}
.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}
.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>
